<?php
	/**
	 * This puts all the information gotten from the form into the database
	 * In short, it checks if the input is correct, then it creates a new user
	 * with the information gotten.
	 * After that it creates a temporary new user again _without_ the password
	 * to see if that user already exists. An existing user very probably has
	 * a different password, so it must only check on username.
	 * Lastly, it compares the result and decides whether to put it in or not
	 */
	
	require_once "../include/User.php";
	require_once "../include/backend/UserDb.php";
	require_once "../include/functions.php";

	if (!hasVal($_POST['username']) || !hasVal($_POST['pass1'])
	    || !hasVal($_POST['pass2']) || !hasVal($_POST['given'])
	    || !hasVal($_POST['surname']) || !hasVal($_POST['nationality']))
		header("Location: ../login.php?act=register&err=empty");
	else if ($_POST['pass1'] != $_POST['pass2'])
		header("Location: ../login.php?err=pwmismatch");
	
	// Last two variables are latitude/longtitude. The user will set these later
	// in his preferences
	$pass = new Password($_POST['pass1']); $pass = $pass->getHash();
	$user = new User(array('username' => addslashes($_POST['username']), 
	                       'pass' => $pass, 'surname' => $_POST['surname'], 
	                       'given' => $_POST['given'], 
	                       'nationality' => $_POST['nationality'], 
	                       'latitude' => 0, 'longtitude' => 0));
	$users = new UserDb();
	$possUser = $users->get(new User($_POST['username']));
	
	if (!isset($possUser->name)) {
		session_start();
		$users->add($user);
		$user->setLoggedIn(true);
		$_SESSION['user'] = $user;
		header("Location: ../login.php?stat=loggedin");
	}
	else
		header("Location: ../login.php?act=register&err=exists");
?>
